package com.atguigu.guli.service.edu.controller.admin;


import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.service.edu.entity.SearchObj;
import com.atguigu.guli.service.edu.entity.Teacher;
import com.atguigu.guli.service.edu.feign.OssFileService;
import com.atguigu.guli.service.edu.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author liujun
 * @since 2021-01-20
 */
//@CrossOrigin
@RestController
@RequestMapping("/admin/edu/teacher")
@Slf4j
public class TeacherController {
    @Autowired
    TeacherService teacherService;

    @Autowired
    OssFileService ossFileService;
//    @GetMapping("/list")
//    public List<Teacher> getTeachers() {
//        final List<Teacher> teachers = teacherService.list(null);
//        return teachers;
//    }

    @ApiOperation("根据关键字查询名字")
    @GetMapping("/listByName/{key}")
    public R listByName(@ApiParam(value = "姓名关键字", required = true) @PathVariable String key) {
        final List<Teacher> teachers = teacherService.list(new QueryWrapper<Teacher>().like("name", key));
        if (!CollectionUtils.isEmpty(teachers)) {
            final List<HashMap<String, String>> nameList = teachers.stream().map(teacher -> {
                final HashMap<String, String> map = new HashMap();
                map.put("value", teacher.getName());
                return map;
            }).collect(Collectors.toList());
            return R.ok().data("nameList", nameList);
        }
        return R.error();
    }

    @ApiOperation("分页讲师列表")
    @GetMapping ("/list/{page}/{limit}")
    public R listPage(@ApiParam(value = "当前页码", required = true) @PathVariable Long page,
                      @ApiParam(value = "每页记录数", required = true) @PathVariable Long limit,
                      @ApiParam(value = "查询表单") SearchObj searchObj) {
        Page<Teacher> pageParam = new Page<>(page, limit);
        IPage<Teacher> pageModel;
        final QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
        if (searchObj.getName() != null) {
            wrapper.like("name", searchObj.getName());
        }
        if (searchObj.getLevel() != null) {
            wrapper.eq("level", searchObj.getLevel());
        }
        if (searchObj.getStartDate() != null && searchObj.getEndDate() != null) {
            wrapper.between("join_date", searchObj.getStartDate(), searchObj.getEndDate());
        }else if(searchObj.getStartDate() != null){
            wrapper.ge("join_date",searchObj.getStartDate());
        }else if(searchObj.getEndDate() != null){
            wrapper.le("join_date",searchObj.getEndDate());
        }
        pageModel = teacherService.page(pageParam, wrapper);
        List<Teacher> records = pageModel.getRecords();
        long total = pageModel.getTotal();
        return R.ok().data("total", total).data("rows", records);
    }

    //根据id删除讲师
    @ApiOperation("根据id删除讲师")
    @DeleteMapping("/remove/{id}")
    public R removeById(@ApiParam(value = "讲师id", required = true) @PathVariable String id) {
        //todo (后期决定是否批量删除)删除讲师头像
        teacherService.removeAvatarById(id);
        //删除讲师
        final boolean res = teacherService.removeById(id);
        if (res) {
            return R.ok().message("删除讲师成功！");
        }
        return R.error().message("删除讲师失败！");
    }

    //根据ids批量删除讲师
    @ApiOperation("根据ids批量删除讲师")
    @DeleteMapping("/batchRemove")
    public R removeByIds(@ApiParam(value = "讲师ids列表", required = true) @RequestBody List<String> ids) {
        final boolean res = teacherService.removeByIds(ids);
        if (res) {
            return R.ok();
        }
        return R.error();
    }

    //保存讲师
    @ApiOperation("保存讲师")
    @PostMapping("/save")
    public R save(@ApiParam(value = "讲师", required = true) @RequestBody Teacher teacher) {
        final boolean res = teacherService.save(teacher);
        if (res) {
            return R.ok();
        }
        return R.error();
    }

    //修改讲师
    @ApiOperation("修改讲师")
    @PutMapping("/update")
    public R update(@ApiParam(value = "讲师", required = true) @RequestBody Teacher teacher) {
        final boolean res = teacherService.saveOrUpdate(teacher);
        if (res) {
            return R.ok();
        }
        return R.error();
    }

    //根据id查询讲师
    @ApiOperation("根据id查询讲师")
    @GetMapping("/get/{id}")
    public R getById(@ApiParam(value = "讲师id", required = true) @PathVariable String id) {
        final Teacher teacher = teacherService.getById(id);
        if (teacher != null) {
            return R.ok().data("teacher", teacher);
        }
        return R.error();
    }
    //根据url删除讲师头像（远程调用oss服务）
    @ApiOperation("根据id删除讲师头像（远程调用oss服务）")
    @DeleteMapping("/remove/avatar")
    public boolean removeAvatar(@ApiParam(value = "讲师id", required = true) @RequestParam(value = "id") String id) {
       return teacherService.removeAvatarById(id);
    }

    //查询所有讲师列表
    @ApiOperation("查询所有讲师列表")
    @GetMapping("/list")
    public R listAllTeachers() {
        final List<Teacher> teachers = teacherService.list(null);
        if (CollectionUtils.isEmpty(teachers)) {
            return R.error().message("获取讲师列表失败！");
        }
        return R.ok().data("items", teachers).message("获取讲师列表成功！");
    }
    @ApiOperation("测试服务调用")
    @GetMapping("test")
    public R test(){
        ossFileService.test();
        return R.ok();
    }

    @ApiOperation("测试并发")
    @GetMapping("test_concurrent")
    public R testConcurrent(){
        ossFileService.test();
        log.info("test_concurrent");
        return R.ok();
    }
    //测试sentinel
    @GetMapping("/message1")
    public String message1() {
        return "message1";
    }
    @GetMapping("/message2")
    public String message2() {
        return "message2";
    }
}

